
var app = getApp()
var Bmob = require('../../utils/bmob.js');
Page({
  data: {
    orderLists: [],
    pages: 1,
    types: {
      0: [undefined, 0, 1, 2, 3],
      1: [undefined, 0, 1, 2, 3],
      2: [undefined, 0, 6, 7],
      3: [undefined, 0, 1, 2],
      5: [undefined, 0, 6, 7]
    },
    noMore: false,
    currentTabIndex: 0,
    currentGoodsType: '',
    goodsTypeList: [],
    isFromBack: false
  },
  onLoad: function (options) {
    this.dataInitial();
  },
  onShow: function () {
    if (this.data.isFromBack) {
      this.setData({
        pages: 1,
        currentTabIndex: 0,
        noMore: false
      });
      this.getOrderList({ tabIndex: 0 });
    } else {
      this.setData({
        isFromBack: true
      })
    }
    // if (!app.getUserInfo().phone) {
    //   app.turnToPage('/pages/bindCellphone/bindCellphone', true);
    // }
  },
  get_goodsTypeList: function () {
    var that = this;
    var GoodsTypeList = Bmob.Object.extend("pages");
    var goodsTypeList = new Bmob.Query(GoodsTypeList);
    goodsTypeList.find({
      success: function (res) {
        that.setData({

          goodsTypeList: res[0].get("goodsTypeList")

        })

      }

    })

  },
  dataInitial: function () {
    this.get_goodsTypeList();
    this.getOrderList({
      tabIndex: 0,
      firstLoad: true
    });
  },


  getOrderList: function (param) {
    var that = this,
      _this = this,
      data = {
        page: that.data.pages,
        page_size: 50
      },
      type;

    if (this.data.goodsTypeList.length == 1) {
      type = this.data.types[this.data.currentGoodsType][param.tabIndex];

      if (type != undefined) {
        data.idx_arr = {
          idx: 'status',
          idx_value: type
        }
      }
    }
    this.data.currentGoodsType && (data.goods_type = this.data.currentGoodsType);

    data.parent_shop_app_id = app.getAppId(); // 获取订单列表时 传parent_shop_app_id获取本店以及所有子店的订单

    if (param.firstLoad) {
      // 进入页面首次请求列表时 没有goodsType值 传入use_default_goods_type
      //data.use_default_goods_type = 1;

    }

    var OrderList = Bmob.Object.extend("orderList");
    var orderlist = new Bmob.Query(OrderList);
    var currentUser = Bmob.User.current();
    var objectId = currentUser.id;
    var isme = new Bmob.User();
    isme.id = objectId;
    console.log(Number(param.tabIndex));
    orderlist.equalTo("current_goods_type", Number(param.tabIndex));
    orderlist.include("sub_shop_info");
    orderlist.descending("createAt");
    orderlist.equalTo("users", isme);

    orderlist.find({
      success: function (res) {
        //var goods=res;
        console.log(res);
        data['orderLists'] = res;
        //data['currentGoodsType'] = res[0].get("current_goods_type");
        // data['pages'] = that.data.pages + 1;
        _this.setData(data);
      },
      error: function (e) {
        console.log(e)

      },
      complete: function (e) {
        console.log(e)
      }

    })

  },
  clickOrderTab: function (e) {
    var dataset = e.target.dataset,
      index = dataset.index,
      data = {};

    data.currentTabIndex = index;
    data['pages'] = 1;
    data['orderLists'] = [];
    data['noMore'] = false;
    data.currentGoodsType = e.currentTarget.dataset.goodsType;

    this.setData(data);
    this.getOrderList({ tabIndex: index });
  },
  getOrderList1: function (param) {
    var that = this,
      data = {
        page: that.data.pages,
        page_size: 50
      },
      type;

    if (this.data.goodsTypeList.length == 1) {
      type = this.data.types[this.data.currentGoodsType][param.tabIndex];

      if (type != undefined) {
        data.idx_arr = {
          idx: 'status',
          idx_value: type
        }
      }
    }
    this.data.currentGoodsType && (data.goods_type = this.data.currentGoodsType);

    data.parent_shop_app_id = app.getAppId(); // 获取订单列表时 传parent_shop_app_id获取本店以及所有子店的订单

    if (param.firstLoad) {
      // 进入页面首次请求列表时 没有goodsType值 传入use_default_goods_type
      data.use_default_goods_type = 1;
    }
    app.sendRequest({
      url: '/index.php?r=AppShop/orderList',
      method: 'post',
      data: data,
      success: function (res) {
        var data = {},
          orders = res.data;

        for (var i = orders.length - 1; i >= 0; i--) {
          var formData = orders[i].form_data;

          if (formData.tostore_data && formData.tostore_data.appointed_time) {
            formData.tostore_data.appointed_time = formData.tostore_data.appointed_time.substr(11, 5);
          }
          orders[i] = formData;
        }

        if (param.scrollLoad) {
          orders = that.data.orderLists.concat(orders);
        }
        data['orderLists'] = orders;
        data['takeoutInfo'] = res.take_out_info;
        data['pages'] = that.data.pages + 1;
        data['noMore'] = res.is_more == 0 ? true : false;
        // data['goodsTypeList'] = res.goods_type_list;
        data['currentGoodsType'] = res.current_goods_type;
        that.setData(data);
      }
    })
  },

  goToOrderDetail: function (e) {
    console.log(e);
    var dataset = e.currentTarget.dataset,

      orderId = dataset.id,
      type = dataset.type,
      franchiseeId = dataset.franchisee,
      queryStr = franchiseeId === app.getAppId() ? '' : '&franchisee=' + franchiseeId,
      router;
    if (type === 'transfer') {
      router = 'transferOrderDetail';
    } else if (type === 'tostore') {
      router = 'tostoreOrderDetail';
    } else if (type === 'eBusiness') {
      router = 'goodsOrderDetail';
    } else if (type === 'takeout') {
      router = 'takeoutOrderDetail';
    } else {
      router = 'orderDetail';
    }
    app.turnToPage('/pages/' + router + '/' + router + '?detail=' + orderId + queryStr);
  },

  cancelOrder: function (e) {
    var orderId = e.currentTarget.dataset.id,
      index = e.currentTarget.dataset.index,
      that = this,
      orderLists = that.data.orderLists;

    var data = {};
    var Order = Bmob.Object.extend("orderList");
    var order = new Bmob.Query(Order);
    // 这个 id 是要修改条目的 id，你在生成这个存储并成功时可以获取到，请看前面的文档

    app.showModal({
      content: '是否取消订单？',
      showCancel: true,
      confirmText: '是',
      cancelText: '否',
      confirm: order.get(orderId, {
        success: function (result) {
          // 回调中可以取得这个 diary 对象的一个实例，然后就可以修改它了
          result.set('status', 7);

          result.save({
            success: function (res) {

              var index = that.data.currentTabIndex,
                data = {};
              data['pages'] = 1;
              that.setData(data);
              that.getOrderList({ tabIndex: index });
            }


          });
          // The object was retrieved successfully.
        },
        error: function (object, error) {
          console.log(error)
        }
      })
    })
  },

  applyDrawback: function (e) {
    var orderId = e.target.dataset.id,
      franchisee = e.target.dataset.franchisee,
      subShopId = franchisee == app.getAppId() ? '' : franchisee,
      that = this;

    app.showModal({
      content: '确定要申请退款？',
      showCancel: true,
      cancelText: '取消',
      confirmText: '确定',
      confirm: function () {
        var OrderList = Bmob.Object.extend("orderList");
        var orderlist = new Bmob.Query(OrderList);
        orderlist.get(orderId, {
          success: function (res) {

            res.set("status", 4);
            res.save(null, {
              success: function () {
                var index = that.data.currentTabIndex,
                  data = {};
                data['pages'] = 1;
                that.setData(data);
                that.getOrderList({ tabIndex: index });
              }

            });
          },


        })

      }
    })
  },
  checkLogistics: function (e) {
    var orderId = e.target.dataset.id;
    app.turnToPage('/pages/logisticsPage/logisticsPage?detail=' + orderId);
  },
  sureReceipt: function (e) {
    var orderId = e.target.dataset.id,
      franchisee = e.target.dataset.franchisee,
      subShopId = franchisee == app.getAppId() ? '' : franchisee,
      that = this;

    app.showModal({
      content: '确定已收到货物？',
      showCancel: true,
      cancelText: '取消',
      confirmText: '确定',
      confirm: function () {
        var OrderList = Bmob.Object.extend("orderList");
        var orderlist = new Bmob.Query(OrderList);
        orderlist.get(orderId, {
          success: function (res) {

            res.set("status", 3);
            res.save(null, {
              success: function () {
                var index = that.data.currentTabIndex,
                  data = {};
                data['pages'] = 1;
                that.setData(data);
                that.getOrderList({ tabIndex: index });
              }

            });

          },


        })


      }
    })
  },
  makeComment: function (e) {
    var orderId = e.target.dataset.id,
      franchiseeId = e.target.dataset.franchisee,
      queryStr = franchiseeId === app.getAppId() ? '' : '&franchisee=' + franchiseeId;
    app.turnToPage('/pages/makeComment/makeComment?detail=' + orderId + queryStr);
  },
  takeoutMakeComment: function (e) {
    var orderId = e.target.dataset.id,
      franchiseeId = e.target.dataset.franchisee,
      queryStr = franchiseeId === app.getAppId() ? '' : '&franchisee=' + franchiseeId;
    app.turnToPage('/pages/takeoutMakeComment/takeoutMakeComment?detail=' + orderId + queryStr);
  },
  verificationCode: function (e) {
    var orderId = e.target.dataset.id;
    var franchiseeId = e.target.dataset.franchisee;
    app.turnToPage('/pages/verificationCodePage/verificationCodePage?detail=' + orderId + '&sub_shop_app_id=' + franchiseeId);
  },
  scrollToListBottom: function () {
    var currentTabIndex = this.data.currentTabIndex;
    if (this.data.noMore) {
      return;
    }
    this.getOrderList({
      tabIndex: currentTabIndex,
      scrollLoad: true
    });
  }
})
